package com.engine.cese.duss.tianyancha.businessinfo.web;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import weaver.common.DateUtil;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.engine.cese.duss.tianyancha.util.HttpClientUtil.sendGetHttpRequest;

/**
 * @Description: 获取天眼查工商基本信息
 * @Author: Dusongsong
 * @Date: 2020/11/17
 */
public class WeaBusinessInfoAction {
    /**
     * 获取天眼查企业基本信息数据
     *
     * @param request
     * @param response
     * @return
     */
    @GET
    @Path("/businessInfo")
    @Produces({MediaType.TEXT_PLAIN})
    public String getBusinessInfo(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        Map<String, Object> apidatas = new HashMap<String, Object>();
        BaseBean baseBean = new BaseBean();
        String addressIP = Util.getIpAddr( request );
        String keyword = Util.null2String( request.getParameter( "keyword" ) );
        JSONObject result = new JSONObject();
        try {
            RecordSet rs = new RecordSet();
            RecordSet rs1 = new RecordSet();
            rs.executeQuery( "select * from uf_tycqyxx where name=?", keyword );
            if (rs.next()) {
                String currentdate = Util.null2String( rs.getString( "currentdate" ) );//当前日期
                String mainid = Util.null2String( rs.getString( "id" ) );//mainid
                long days = getDays( currentdate.substring( 0, 10 ) );
                int setdays = Util.getIntValue( baseBean.getPropValue( "tianyancha", "setdays" ) );
                if (days < setdays) {
                    String historyNames = Util.null2String( rs.getString( "historyNames" ) );//曾⽤名
                    String regStatus = Util.null2String( rs.getString( "regStatus" ) );//企业状态
                    String cancelDate = Util.null2String( rs.getString( "cancelDate" ) );//注销⽇期
                    String regCapital = Util.null2String( rs.getString( "regCapital" ) );//注册资本
                    String city = Util.null2String( rs.getString( "city" ) );//市
                    String staffNumRange = Util.null2String( rs.getString( "staffNumRange" ) );//⼈员规模
                    String industry = Util.null2String( rs.getString( "industry" ) );//⾏业
                    String historyNameList = Util.null2String( rs.getString( "historyNameList" ) );//曾⽤名列表
                    String bondNum = Util.null2String( rs.getString( "bondNum" ) );//股票号
                    String type = Util.null2String( rs.getString( "type1" ) );//法⼈类型，1 ⼈ 2 公司
                    String bondName = Util.null2String( rs.getString( "bondName" ) );//股票名
                    String updateTimes = Util.null2String( rs.getString( "updateTimes" ) );//更新时间
                    String revokeDate = Util.null2String( rs.getString( "revokeDate" ) );//吊销⽇期
                    String legalPersonName = Util.null2String( rs.getString( "legalPersonName" ) );//法⼈
                    String revokeReason = Util.null2String( rs.getString( "revokeReason" ) );//吊销原因
                    String regNumber = Util.null2String( rs.getString( "regNumber" ) );//注册号
                    String property3 = Util.null2String( rs.getString( "property3" ) );//英⽂名
                    String creditCode = Util.null2String( rs.getString( "creditCode" ) );//统⼀社会信⽤代码
                    String usedBondName = Util.null2String( rs.getString( "usedBondName" ) );//股票曾⽤名
                    String fromTime = Util.null2String( rs.getString( "fromTime" ) );//经营开始时间
                    String approvedTime = Util.null2String( rs.getString( "approvedTime" ) );//核准时间
                    String socialStaffNum = Util.null2String( rs.getString( "socialStaffNum" ) );//参保⼈数
                    String alias = Util.null2String( rs.getString( "alias" ) );//简称
                    String companyOrgType = Util.null2String( rs.getString( "companyOrgType" ) );//企业类型
                    String actualCapitalCurrency = Util.null2String( rs.getString( "actualCapitalCurrency" ) );//实收注册资本币种 ⼈⺠币 美元 欧元 等
                    String qyid = Util.null2String( rs.getString( "qyid" ) );//企业id
                    String orgNumber = Util.null2String( rs.getString( "orgNumber" ) );//组织机构代码
                    String cancelReason = Util.null2String( rs.getString( "cancelReason" ) );//注销原因
                    String toTime = Util.null2String( rs.getString( "toTime" ) );//经营结束时间
                    String actualCapital = Util.null2String( rs.getString( "actualCapital" ) );//实收注册资⾦
                    String estiblishTime = Util.null2String( rs.getString( "estiblishTime" ) );//成⽴⽇期
                    String regInstitute = Util.null2String( rs.getString( "regInstitute" ) );//登记机关
                    String taxNumber = Util.null2String( rs.getString( "taxNumber" ) );//纳税⼈识别号
                    String businessScope = Util.null2String( rs.getString( "businessScope" ) );//经营范围
                    String regLocation = Util.null2String( rs.getString( "regLocation" ) );//注册地址
                    String regCapitalCurrency = Util.null2String( rs.getString( "regCapitalCurrency" ) );//注册资本币种 ⼈⺠币 美元 欧元 等
                    String tags = Util.null2String( rs.getString( "tags" ) );//企业标签
                    String district = Util.null2String( rs.getString( "district" ) );//区
                    String name = Util.null2String( rs.getString( "name" ) );//企业名
                    String bondType = Util.null2String( rs.getString( "bondType" ) );//股票类型
                    String percentileScore = Util.null2String( rs.getString( "percentileScore" ) );//企业评分
                    String isMicroEnt = Util.null2String( rs.getString( "isMicroEnt" ) );//是否是⼩微企业 0不是 1是
                    String base = Util.null2String( rs.getString( "base" ) );//省份简称
                    result.put( "historyNames", historyNames );//曾⽤名
                    result.put( "regStatus", regStatus );//企业状态
                    result.put( "cancelDate", cancelDate );//注销⽇期
                    result.put( "regCapital", regCapital );//注册资本
                    result.put( "city", city );//市
                    result.put( "staffNumRange", staffNumRange );//⼈员规模
                    result.put( "industry", industry );//⾏业
                    result.put( "historyNameList", historyNameList );//曾⽤名列表
                    result.put( "bondNum", bondNum );//股票号
                    result.put( "type", type );//法⼈类型，1 ⼈ 2 公司
                    result.put( "bondName", bondName );//股票名
                    result.put( "updateTimes", updateTimes );//更新时间
                    result.put( "revokeDate", revokeDate );//吊销⽇期
                    result.put( "legalPersonName", legalPersonName );//法⼈
                    result.put( "revokeReason", revokeReason );//吊销原因
                    result.put( "regNumber", regNumber );//注册号
                    result.put( "property3", property3 );//英⽂名
                    result.put( "creditCode", creditCode );//统⼀社会信⽤代码
                    result.put( "usedBondName", usedBondName );//股票曾⽤名
                    result.put( "fromTime", fromTime );//经营开始时间
                    result.put( "approvedTime", approvedTime );//核准时间
                    result.put( "socialStaffNum", socialStaffNum );//参保⼈数
                    result.put( "alias", alias );//简称
                    result.put( "companyOrgType", companyOrgType );//企业类型
                    result.put( "actualCapitalCurrency", actualCapitalCurrency );//实收注册资本币种 ⼈⺠币 美元 欧元 等
                    result.put( "id", qyid );//企业id
                    result.put( "orgNumber", orgNumber );//组织机构代码
                    result.put( "cancelReason", cancelReason );//注销原因
                    result.put( "toTime", toTime );//经营结束时间
                    result.put( "actualCapital", actualCapital );//实收注册资⾦
                    result.put( "estiblishTime", estiblishTime );//成⽴⽇期
                    result.put( "regInstitute", regInstitute );//登记机关
                    result.put( "taxNumber", taxNumber );//纳税⼈识别号
                    result.put( "businessScope", businessScope );//经营范围
                    result.put( "regLocation", regLocation );//注册地址
                    result.put( "regCapitalCurrency", regCapitalCurrency );//注册资本币种 ⼈⺠币 美元 欧元 等
                    result.put( "tags", tags );//企业标签
                    result.put( "district", district );//区
                    result.put( "name", name );//企业名
                    result.put( "bondType", bondType );//股票类型
                    result.put( "percentileScore", percentileScore );//企业评分
                    result.put( "isMicroEnt", isMicroEnt );//是否是⼩微企业 0不是 1是
                    result.put( "base", base );//省份简称
                    //明细数据
                    JSONObject industryAll = new JSONObject();
                    rs1.executeQuery( "select categorymiddle,categorybig,category,categorysmall from uf_tycqyxx_dt1 where mainid=?", mainid );
                    rs1.next();
                    String categoryMiddle = Util.null2String( rs1.getString( "categoryMiddle" ) );//国⺠经济⾏业分类中类
                    String categoryBig = Util.null2String( rs1.getString( "categoryBig" ) );//国⺠经济⾏业分类⼤类
                    String category = Util.null2String( rs1.getString( "category" ) );//国⺠经济⾏业分类⻔类
                    String categorySmall = Util.null2String( rs1.getString( "categorySmall" ) );//国⺠经济⾏业分类⼩类
                    industryAll.put( "categoryMiddle", categoryMiddle );
                    industryAll.put( "categoryBig", categoryBig );
                    industryAll.put( "category", category );
                    industryAll.put( "categorySmall", categorySmall );
                    result.put( "industryAll", industryAll );
                } else {
                    rs.executeUpdate("delete uf_tycqyxx where id=?",mainid);
                    rs.executeUpdate("delete uf_tycqyxx_dt1 where mainid=?",mainid);
                    String url = baseBean.getPropValue( "tianyancha", "url" );
                    String TOKEN = baseBean.getPropValue( "tianyancha", "token" );
                    String URL = url + "?keyword=" + keyword;
                    String CODE = "UTF-8";
                    JSONObject resultJson = sendGetHttpRequest( URL, TOKEN, CODE );
                    String reason = resultJson.getString( "reason" );//错误信息
                    String errorcode = resultJson.getString( "error_code" );//状态码
                    result = JSONObject.parseObject( resultJson.getString( "result" ) );
                    if ("ok".equals( reason ) && "0".equals( errorcode )) {
                        if (addBusinessInfo( result )) {
                            addLogInfo( addressIP, errorcode, reason, keyword );
                        }
                    }
                }
            } else {
                String url = baseBean.getPropValue( "tianyancha", "url" );
                String TOKEN = baseBean.getPropValue( "tianyancha", "token" );
                String URL = url + "?keyword=" + keyword;
                String CODE = "UTF-8";
                JSONObject resultJson = sendGetHttpRequest( URL, TOKEN, CODE );
                String reason = resultJson.getString( "reason" );//错误信息
                String errorcode = resultJson.getString( "error_code" );//状态码
                result = JSONObject.parseObject( resultJson.getString( "result" ) );
                if ("ok".equals( reason ) && "0".equals( errorcode )) {
                    if (addBusinessInfo( result )) {
                        addLogInfo( addressIP, errorcode, reason, keyword );
                    }
                }
            }
            apidatas.put( "result", result );
        } catch (Exception e) {
            e.printStackTrace();
            apidatas.put( "api_status", false );
            apidatas.put( "error_message", "获取天眼查数据异常" );
        }
        return JSONObject.toJSONString( apidatas );
    }

    //天眼查-企业基本信息入库
    public static boolean addBusinessInfo(JSONObject result) {
        boolean flag = false;
        RecordSet rs = new RecordSet();
        RecordSet rs1 = new RecordSet();
        String historynames = Util.null2String( result.getString( "historyNames" ) );//曾⽤名
        String regstatus = Util.null2String( result.getString( "regStatus" ) );//企业状态
        String canceldate = Util.null2String( result.getString( "cancelDate" ) );//注销⽇期
        String regcapital = Util.null2String( result.getString( "regCapital" ) );//注册资本
        String city = Util.null2String( result.getString( "city" ) );//市
        String staffnumrange = Util.null2String( result.getString( "staffNumRange" ) );//⼈员规模
        String industry = Util.null2String( result.getString( "industry" ) );//⾏业
        String historynamelist = Util.null2String( result.getString( "historyNameList" ) );//曾⽤名列表
        String bondnum = Util.null2String( result.getString( "bondNum" ) );//股票号
        String type = Util.null2String( result.getString( "type" ) );//法⼈类型，1 ⼈ 2 公司
        String bondname = Util.null2String( result.getString( "bondName" ) );//股票名
        String updatetimes = Util.null2String( result.getString( "updateTimes" ) );//更新时间
        String revokedate = Util.null2String( result.getString( "revokeDate" ) );//吊销⽇期
        String legalpersonname = Util.null2String( result.getString( "legalPersonName" ) );//法⼈
        String revokereason = Util.null2String( result.getString( "revokeReason" ) );//吊销原因
        String regnumber = Util.null2String( result.getString( "regNumber" ) );//注册号
        String property3 = Util.null2String( result.getString( "property3" ) );//英⽂名
        String creditcode = Util.null2String( result.getString( "creditCode" ) );//统⼀社会信⽤代码
        String usedbondname = Util.null2String( result.getString( "usedBondName" ) );//股票曾⽤名
        String fromtime = Util.null2String( result.getString( "fromTime" ) );//经营开始时间
        String approvedtime = Util.null2String( result.getString( "approvedTime" ) );//核准时间
        String socialstaffnum = Util.null2String( result.getString( "socialStaffNum" ) );//参保⼈数
        String alias = Util.null2String( result.getString( "alias" ) );//简称
        String companyorgtype = Util.null2String( result.getString( "companyOrgType" ) );//企业类型
        String actualcapitalcurrency = Util.null2String( result.getString( "actualCapitalCurrency" ) );//实收注册资本币种 ⼈⺠币 美元 欧元 等
        String qyid = Util.null2String( result.getString( "id" ) );//企业id
        String orgnumber = Util.null2String( result.getString( "orgNumber" ) );//组织机构代码
        String cancelreason = Util.null2String( result.getString( "cancelReason" ) );//注销原因
        String totime = Util.null2String( result.getString( "toTime" ) );//经营结束时间
        String actualcapital = Util.null2String( result.getString( "actualCapital" ) );//实收注册资⾦
        String estiblishtime = Util.null2String( result.getString( "estiblishTime" ) );//成⽴⽇期
        String reginstitute = Util.null2String( result.getString( "regInstitute" ) );//登记机关
        String taxnumber = Util.null2String( result.getString( "taxNumber" ) );//纳税⼈识别号
        String businessscope = Util.null2String( result.getString( "businessScope" ) );//经营范围
        String reglocation = Util.null2String( result.getString( "regLocation" ) );//注册地址
        String regcapitalcurrency = Util.null2String( result.getString( "regCapitalCurrency" ) );//注册资本币种 ⼈⺠币 美元 欧元 等
        String tags = Util.null2String( result.getString( "tags" ) );//企业标签
        String district = Util.null2String( result.getString( "district" ) );//区
        String name = Util.null2String( result.getString( "name" ) );//企业名
        String bondtype = Util.null2String( result.getString( "bondType" ) );//股票类型
        String percentilescore = Util.null2String( result.getString( "percentileScore" ) );//企业评分
        String ismicroent = Util.null2String( result.getString( "isMicroEnt" ) );//是否是⼩微企业 0不是 1是
        String base = Util.null2String( result.getString( "base" ) );//省份简称
        JSONObject industryall = JSONObject.parseObject( result.getString( "industryAll" ) );//国⺠经济⾏业分类
        String categorymiddle = Util.null2String( industryall.getString( "categoryMiddle" ) );//国⺠经济⾏业分类中类
        String categorybig = Util.null2String( industryall.getString( "categoryBig" ) );//国⺠经济⾏业分类⼤类
        String category = Util.null2String( industryall.getString( "category" ) );//国⺠经济⾏业分类⻔类
        String categorysmall = Util.null2String( industryall.getString( "categorySmall" ) );//国⺠经济⾏业分类⼩类
        String currentdate = DateUtil.getFullDate();
        String sql = "insert into uf_tycqyxx(currentdate,type1,qyid,historynames,regstatus,canceldate," +
                "regcapital,city,staffnumrange,industry,historynamelist,bondnum,bondname,updatetimes,revokedate," +
                "legalpersonname,revokereason,regnumber,property3,creditcode,usedbondname,fromtime,approvedtime," +
                "socialstaffnum,alias,companyorgtype,actualcapitalcurrency,orgnumber,cancelreason,totime," +
                "actualcapital,estiblishtime,reginstitute,taxnumber,businessscope,reglocation,regcapitalcurrency," +
                "tags,district,name,bondtype,percentilescore,ismicroent,base) values (?,?,?,?,?,?,?,?,?,?,?,?,?," +
                "?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        Object[] params = {currentdate, type, qyid, historynames, regstatus, canceldate, regcapital, city, staffnumrange,
                industry, historynamelist, bondnum, bondname, updatetimes, revokedate, legalpersonname, revokereason,
                regnumber, property3, creditcode, usedbondname, fromtime, approvedtime, socialstaffnum, alias, companyorgtype,
                actualcapitalcurrency, orgnumber, cancelreason, totime, actualcapital, estiblishtime, reginstitute, taxnumber,
                businessscope, reglocation, regcapitalcurrency, tags, district, name, bondtype, percentilescore, ismicroent, base};
        if (rs.executeUpdate( sql, params )) {
            rs1.executeQuery( "select id from uf_tycqyxx where creditcode=?", creditcode );
            rs1.next();
            String mainid = Util.null2String( rs1.getString( "id" ) );//mainid
            rs.writeLog( "------------------------mainid=" + mainid );
            Object[] params1 = {mainid, categorymiddle, categorybig, category, categorysmall};
            String sql1 = "insert into uf_tycqyxx_dt1(mainid,categorymiddle,categorybig,category,categorysmall) values (?,?,?,?,?)";
            rs1.executeUpdate( sql1, params1 );
            flag = true;
        }

        return flag;
    }

    //插入天眼查接口调用日志
    public static boolean addLogInfo(String clientip, String errorcode, String reason, String keyword) {
        RecordSet rs = new RecordSet();
        boolean flag = false;
        String name = "http://open.api.tianyancha.com/services/open/ic/baseinfo/normal";//接口名称
        String createdate = DateUtil.getFullDate();
        ;//调用时间
        String times = "1";//调用次数
        UUID MR_UUID = UUID.randomUUID();
        String uuid = MR_UUID.toString();
        String sql = "insert into uf_tycinvokelog (name,clientip,errorcode,reason,createdate,times,keyword,uuid) " +
                "values (?,?,?,?,?,?,?,?)";
        Object[] params = {name, clientip, errorcode, reason, createdate, times, keyword, uuid};
        if (rs.executeUpdate( sql, params )) {
            flag = true;
        }
        return flag;
    }

    //获取天数
    public static long getDays(String date) {
        long days = 0L;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd" );
            Date d1 = sdf.parse( date );
            long ts1 = d1.getTime();
            Date d2 = sdf.parse( DateUtil.getCurrentDate() );
            long ts2 = d2.getTime();
            days = (ts2 - ts1) / (1000 * 60 * 60 * 24);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return days;
    }

}
